<template>
    <el-card shadow="always">
        <el-row class="margin-bottom-20">
            <el-col :span="8">
                <el-input placeholder="请输入用户名关键字(默认查询全部)" v-model="params.query">
                    <template slot="append">
                        <el-button icon="el-icon-search" @click="searchBykeyWord()"></el-button>
                    </template>
                </el-input>
            </el-col>
            <el-col :span="4">
                <el-button class="margin-left-10" type="primary" @click="isShowAdd=true">添加新用户</el-button>
            </el-col>
        </el-row>
        <el-table border :data="users" :max-height="h-230" v-loading="isLoading">
            <el-table-column label="序号" width="80" type="index" prop="index"></el-table-column>
            <el-table-column label="姓名" prop="username"></el-table-column>
            <el-table-column label="邮箱" prop="email"></el-table-column>
            <el-table-column label="电话号码" prop="mobile"></el-table-column>
            <el-table-column label="角色" prop="role_name"></el-table-column>
            <el-table-column label="状态" width="80">
                <template v-slot:default="{ row }">
                    <el-switch v-model="row.mg_state" @change="changeUserState(row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
				<template v-slot:default="{ row }">
					<el-tooltip effect="dark" content="信息更新" placement="top-start">
						<el-button type="primary" icon="el-icon-edit" size="mini" @click="showModify(row.id)"></el-button>
					</el-tooltip>
					<el-tooltip effect="dark" content="账号删除" placement="top-start">
						<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(row.id)"></el-button>
					</el-tooltip>
					<el-tooltip effect="dark" content="角色分配" placement="top-start">
						<el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetting(row)"></el-button>
					</el-tooltip>
				</template>
            </el-table-column>
        </el-table>
		<el-pagination class="margin-top-20" layout="total, sizes, prev, pager, next, jumper"
			:page-sizes="[5, 10, 15, 20]"
			:page-size="params.pagesize"
			:current-page="params.pagenum"
			:total="total"
			@size-change="sizeChangeCallback"
			@current-change="currentChangeCallback"
		></el-pagination>
		<el-dialog
			title="管理员信息修改"
			:visible.sync="isShowModify"
			width="40%"
		>
			<el-form :model="modifyUser" :rules="userRule" ref="modifyUser" label-width="100px">
				<el-form-item label="用户名">
					<el-input :value="modifyUser.username" readonly></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="modifyUser.email" placeholder="请输入邮箱"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="mobile">
					<el-input v-model="modifyUser.mobile" placeholder="请输入手机号码"></el-input>
				</el-form-item>
			</el-form>
			<template v-slot:footer>
				<span class="dialog-footer">
					<el-button @click="isShowModify = false">取 消</el-button>
					<el-button type="primary" @click="changeUserCallback">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog
			title="管理员角色分配"
			:visible.sync="isShowSeting"
			width="40%"
		>
			<el-form :model="settingUser" :rules="userRule" ref="settingUser" label-width="100px">
				<el-form-item label="用户名">
					<el-input :value="settingUser.username" readonly></el-input>
				</el-form-item>
				<el-form-item label="当前角色">
					<el-input :value="settingUser.role_name" readonly></el-input>
				</el-form-item>
				<el-form-item label="分配新角色" prop="rid">
					<el-select v-model="settingUser.rid" placeholder="选择角色" style="width:100%">
						<el-option
							v-for="role in roles"
							:key="role.id"
							:label="role.roleName"
							:value="role.id"
						></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<template v-slot:footer>
				<span class="dialog-footer">
					<el-button @click="isShowSeting = false">取 消</el-button>
					<el-button type="primary" @click="settingUserRole">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog
			title="管理员添加"
			:visible.sync="isShowAdd"
			width="40%"
		>
			<el-form :model="addUser" :rules="userRule" ref="addUser" label-width="100px">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="addUser.username" placeholder="请输入用户名"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="addUser.password" :show-password="true" placeholder="请输入密码"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="addUser.email" placeholder="请输入邮箱"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="mobile">
					<el-input v-model="addUser.mobile" placeholder="请输入电话号码"></el-input>
				</el-form-item>
			</el-form>
			<template v-slot:footer>
				<span class="dialog-footer">
					<el-button @click="isShowAdd = false">取 消</el-button>
					<el-button type="primary" @click="addUserCallback">确 定</el-button>
				</span>
			</template>
		</el-dialog>
    </el-card>
</template>

<script>
import { userRule } from '@/rules/userRules.js';
import { 
	loadUserList,
	changeUserState,
	removeUser,
	loadUserById,
	modfilyUser,
	settingUserRole,
	addUser
} from '@/api/user.js';
import {
	getAllroles
} from '@/api/roles.js'

export default {
	props:["h"],
    data() {
        return {
			isLoading:false,
			isShowModify:false,
			isShowSeting:false,
			isShowAdd:false,
			userRule:userRule,
			roles:{},
			modifyUser:{
				id:0,
				username:"",
				email:"",
				mobile:""
			},
			settingUser:{
				id:0,
				username:"",
				role_name:"",
				rid:null
			},
			addUser:{
				username:"",
				password:"",
				email:"",
				mobile:""
			},
            params:{
				query:"",
                pagenum:1,
                pagesize:5
            },
            users:[],
            total:0
        }
    },
    methods:{
		sizeChangeCallback(newSize){
			this.params.pagenum = 1;
			this.params.pagesize = newSize;
			this.loadUsers();
		},
		currentChangeCallback(currentPage){
			this.params.pagenum = currentPage;
			this.loadUsers();
		},
		async loadUsers(){
			this.isLoading = true;
			let data = await loadUserList(this.params);
			this.isLoading = false;
			if(!data) return;
			this.users = data.users;
			this.total = data.total;
		},
		searchBykeyWord(){
			this.params.pagenum = 1;
			this.loadUsers();
		},
        async changeUserState(user){
			let { mg_state } =  await changeUserState(user.id,user.mg_state);
			if(mg_state!=user.mg_state){
				this.$notify.error(`管理员"${user.username}" : 状态更新失败`);
			}
        },
		async removeUser(userId){
			await removeUser(userId);
			this.loadUsers();
        },
		async showModify(userId){
			let user = await loadUserById(userId);
			if(user==null) return;
			this.modifyUser = user;
			this.isShowModify = true;
		},
		changeUserCallback(){
			this.$refs.modifyUser.validate(async (flag) => {
                if(flag){
					let result = await modfilyUser(this.modifyUser.id,{
						username:this.modifyUser.username,
						email:this.modifyUser.email,
						mobile:this.modifyUser.mobile
					});
					if( !result ) return;
					this.isShowModify = false;
					this.$notify.success(`管理员"${result.username}" : 信息更新成功`);
					this.loadUsers();
				}
            });
		},
		async showSetting(user){
			let roles = await getAllroles();
			let tempRoles = [];
			for (let item of roles) {
				let { id,roleName } = item;
				tempRoles.push({ id,roleName })
			}
			this.roles = tempRoles;
			this.settingUser.id = user.id;
			this.settingUser.username = user.username;
			this.settingUser.role_name = user.role_name;
			this.isShowSeting = true;
		},
		settingUserRole(){
			this.$refs.settingUser.validate(async (flag) => {
                if(flag){
					let result = await settingUserRole(this.settingUser.id,this.settingUser.rid);
					if( !result ) return;
					this.isShowSeting = false;
					this.$notify.success(`管理员"${result.username}" : 账号角色分配成功`);
					this.loadUsers();
				}
            });
		},
		addUserCallback(){
			this.$refs.addUser.validate(async (flag) => {
                if(flag){
					let result = await addUser(this.addUser);
					console.log(result);
					if( !result ) return;
					this.isShowAdd = false;
					this.$notify.success(`管理员"${result.username}" : 账号添加成功`);
					this.loadUsers();
				}
            } )
		}
    },
    created(){
        this.loadUsers();
    }
}
</script>